package com.hyh.eblog.schedules;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyh.eblog.entity.Post;
import com.hyh.eblog.service.PostService;
import com.hyh.eblog.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时更新浏览量
 *
 * @author Summerday
 */
@Component
@EnableScheduling
public class ViewCountAsyTask {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    PostService postService;

    //https://cron.qqe2.com/
    @Scheduled(cron = "0/10 * * * * *")
    public void task() {
        Set<String> keys = redisTemplate.keys("rank:post:*");
        List<String> ids = new ArrayList<>();

        for (String key : keys) {
            String postId = key.substring("rank:post:".length());
            if (redisUtil.hHasKey(key, "post:viewCount")) {
                ids.add(postId);
            }
        }
        if (ids.isEmpty()) return;
        //需要更新阅读量的post
        List<Post> posts = postService.list(new QueryWrapper<Post>().in("id", ids));

        posts.forEach(post -> {
            Integer viewCount = (Integer) redisUtil.hget("rank:post:" + post.getId(), "post:viewCount");
            post.setViewCount(viewCount);
        });

        if (posts.isEmpty()) return;
        boolean isSuccess = postService.updateBatchById(posts);
        if (isSuccess) {
            ids.forEach(id -> {
                System.out.println("更新成功 -> 当前的时间为 : " + DateUtil.now() + "更新文章编号为 :" + id);
                redisUtil.hdel("rank:post:" + id, "post:viewCount");

            });
        }
    }
}
